import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/models/report/assignmentStudentDetail.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';

// ignore: must_be_immutable
class HomeworkDetailDataGrid extends StatelessWidget {
  HomeworkDetailDataGrid(this.assignmentItems, this.isOverdue);

  bool isOverdue;
  List<AssignmentStudentDetail> assignmentItems;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();

  @override
  Widget build(BuildContext context) {
    Log.debug('build AssingmentDetailDataGrid');

    return this.assignmentItems.isNotEmpty
        ? Column(children: [Expanded(child: _buildDataGrid(isOverdue))])
        : Center(child: Text('Data not available ...'));
  }

  SfDataGrid _buildDataGrid(bool isOverdue) {
    return SfDataGrid(
      source: AssignmentDataGridSource(
          items: assignmentItems, isOverdue: isOverdue),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      allowSorting: true,
      allowTriStateSorting: true,
      allowSwiping: false,
      controller: _dataGridController,
      navigationMode: GridNavigationMode.row,
      endSwipeActionsBuilder:
          (BuildContext context, DataGridRow row, int rowIndex) {
        return GestureDetector(
            onTap: () {},
            child: Container(
                color: Colors.redAccent,
                child: Center(
                  child: Icon(Icons.delete),
                )));
      },
      columns: <GridColumn>[
        GridColumn(
          width: 180,
          columnName: 'BookTitle',
          label: buildDataGridColumnLabel('Book Title'),
        ),
        GridColumn(
          width: 200,
          columnName: 'EnBookTitle',
          label: buildDataGridColumnLabel('English Book Title'),
        ),
        GridColumn(
          width: 180,
          columnName: 'Progress',
          label: buildDataGridColumnLabel('Progress'),
        ),
        GridColumn(
          columnName: 'Read',
          width: isWebOrDesktop ? 120 : 120,
          label: buildDataGridColumnLabel('Read'),
        ),
        GridColumn(
          columnName: 'Quiz',
          width: isWebOrDesktop ? 120 : 120,
          label: buildDataGridColumnLabel('Quiz'),
        ),
        GridColumn(
          columnName: 'Percentage',
          width: isWebOrDesktop ? 140 : 140,
          label: buildDataGridColumnLabel('Highest Quiz Percentage'),
        ),
        GridColumn(
          columnName: 'Recording',
          width: isWebOrDesktop ? 120.0 : 120.0,
          label: buildDataGridColumnLabel('Recording'),
        ),
        GridColumn(
          columnName: 'Writing',
          width: isWebOrDesktop ? 120.0 : 120.0,
          label: buildDataGridColumnLabel('Writing'),
        ),
        GridColumn(
          columnName: 'IsOverdue',
          width: isWebOrDesktop ? 120.0 : 120.0,
          visible: false,
          label: buildDataGridColumnLabel('IsOverdue'),
        ),
      ],
    );
  }
}

class AssignmentDataGridSource extends DataGridSource {
  AssignmentDataGridSource(
      {required List<AssignmentStudentDetail> items, required bool isOverdue}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'BookTitle', value: dataGridRow.bookName),
              DataGridCell<String>(
                  columnName: 'EnBookTitle',
                  value: dataGridRow.englishBookTitle),
              DataGridCell<bool>(
                  columnName: 'Progress', value: dataGridRow.complete),
              DataGridCell<int>(
                  columnName: 'Read', value: dataGridRow.readCount),
              DataGridCell<int>(
                  columnName: 'Quiz', value: dataGridRow.quizCount),
              DataGridCell<int>(
                  columnName: 'Percentage', value: dataGridRow.percentage),
              DataGridCell<String>(
                  columnName: 'Recording',
                  value: dataGridRow.recordingReport?.status ?? null),
              DataGridCell<String>(
                  columnName: 'Writing',
                  value: dataGridRow.writingReport?.status ?? null),
              DataGridCell<bool>(columnName: 'IsOverdue', value: isOverdue),
            ]))
        .toList();
  }

  final box = Hive.box('appconfig');

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    // bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
    //     Constants.NanhaiRole_Teacher;
    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Progress') {
            var isOverdue = row
                .getCells()
                .where((element) => element.columnName == 'IsOverdue')
                .first
                .value;
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value
                    ? "Completed"
                    : isOverdue
                        ? "InCompleted"
                        : "In Progress",
                overflow: TextOverflow.ellipsis,
                style: Get.textTheme.bodySmall,
              ),
            );
          } else if (dataGridCell.columnName == "Percentage") {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value != null ? "${dataGridCell.value}%" : "--",
                softWrap: true,
                style: Get.textTheme.bodySmall,
                overflow: TextOverflow.ellipsis,
              ),
            );
          } else if (dataGridCell.columnName == "Writing" ||
              dataGridCell.columnName == "Recording") {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value != null ? dataGridCell.value : "--",
                softWrap: true,
                style: Get.textTheme.bodySmall,
                overflow: TextOverflow.ellipsis,
              ),
            );
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value != null
                      ? dataGridCell.value.toString()
                      : "--",
                  softWrap: true,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
